<?php
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use App\Http\Controllers\AdminController;
use App\Models\Defines\Defines;
use App\Models\Defines\DefinesTranslation;
use App\Models\Configure\Group;
use App\Services\QiniuServices;
use Validator;
use DB;

class DefinesController extends AdminController
{

    public function index()
    {
        $Group = Group::get();
        return view('admin.defines.index',compact('Group'));
    }

    public function data(Request $request)
    {
        $lang = $request->lang??lang();
        $model = DefinesTranslation::query();
        $model = $model->where('locale',$lang);
		$groupid=$request->get('group_id');
		$keyword=$request->get('name');

        if ($groupid) {
            $model = $model->where('group_id', $groupid);
        }


        if ($keyword) {
            $model = $model->where('name', 'like',"%{$keyword}%")->orWhere('name', 'like', "%{$keyword}%");
        }


        $res = $model->orderBy('id', 'desc')->paginate($request->get('limit', 10));
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res->total(),
            'data' => $res->items()
        ];
        return response()->json($data);
    }
 
    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
 		$rules= [
            'name' => 'required|unique:defines_translations|max:255',
			'keys'  => 'required|min:2|max:20|unique:defines_translations',
            'value' => 'required',
        ];
		
		$messages = [
			'name' => '配置名 :attribute 称已存在,请换个名称',
			'keys' => 'keys :attribute已存在,请重试!.',
			'value' => '配置值 :attribute不能为空！',
		];
		
		$validator = Validator::make($request->all(), $rules, $messages);
		$errors = $validator->errors();
        if ($validator->fails()) {
          return Response::json(['code' => 1, 'msg' => $errors->first(), 'data' => $errors->first(), 'url' => route('admin.defines')]);   
        }
 
 
 
        DB::beginTransaction();
        try {
            $Defines = new Defines();
            $Defines->title = $request->name;
            foreach (config('translatable.locales') as $locale => $item) {
				$defines = $this->createItem($Defines,$request,$locale);
            }
            if($Defines->save() && $this->setServiceProvider($request->keys)){
				 DB::commit();
				 return Response::json(['code' => 0, 'msg' => '添加成功', 'data' => '添加成功', 'url' => route('admin.defines')]);
			}
        } catch (\Exception $exception) {
            DB::rollback();
        } 

        return response()->json(['code' => 0, 'msg' => '系统错误']);
    }


    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {

            $id = (int)$request->get('defines_mid');
            $mid = $request->get('id');
            if(empty($id))  return Response::json(['code' => 1, 'msg' => '非法操作']);
            if(empty($mid))  return Response::json(['code' => 1, 'msg' => '非法操作']);
            $data = $request->except(['_token', 'file']);
			$request = (object)$data;
            $defines = Defines::whereTranslation('id',$mid)->first();
            $sonDefines = DefinesTranslation::find($mid);
			 
			//更新前 删除旧的文件
			$this->fileDestroy($sonDefines->keys);			
 
			DB::beginTransaction();
			try {
			 
				foreach (config('translatable.locales') as $locale => $item) {
	 
						if(!$defines->hasTranslation($locale)){
							$defines = $this->createItem($defines,$request,$locale);
						}else{
							$defines->translateOrNew($locale)->group_id = $request->group_id??1;

						}
				}
				$defines->save();
				$sonDefines->update($data);

				if($sonDefines->update($data)){
				DB::commit();

				}else{
				return response()->json(['code' => 1, 'msg' => '系统错误']);
				}

				if($this->setServiceProvider($request->keys)){


				return response()->json(['code' => 0, 'msg' => '更新成功']);
				}

        } catch (\Exception $exception) {
            DB::rollback();
        }
       
        return response()->json(['code' => 1, 'msg' => '系统错误']);
    }

    public function updateajax(Request $request){ }


    public function fileDestroy($keys){
		if(empty($keys)) return false;
        $path = app_path('Tagserver/');
		//文件名
		$fileName = $path.ucfirst($keys)."ServiceProvider.php";
		delFile($fileName);
		return 1;

	}


    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request,QiniuServices $qiniu)
    {
        $ids = (array)$request->get('ids');
        if (empty($ids)) {
            return response()->json(['code' => 1, 'msg' => '请选择删除项']);
        }
		
        DB::beginTransaction();
        try { 
            
			//删除云端资源
			foreach($ids as $id){
			  $sonDefines = DefinesTranslation::find($id);	
              $defines = Defines::where('mid',$sonDefines->defines_mid)->first();
				foreach ($defines->translations as $item) {
					$qiniu->objFromDelete($item); 
                    $this->fileDestroy($item->keys);
				}
				$defines->delete();
			}			
			DB::commit();
			\Artisan::call('view:clear');
			return response()->json(['code' => 0, 'msg' => '删除成功']);
		 
		
        } catch (\Exception $exception) {
            DB::rollback();
        }

        return response()->json(['code' => 1, 'msg' => '删除失败']);
    }

	private function createItem($Defines,$request,$locale){
		    $Defines->translateOrNew($locale)->group_id = $request->group_id??1;
			$Defines->translateOrNew($locale)->name = $request->name; 
			$Defines->translateOrNew($locale)->keys = $request->keys; 
			$Defines->translateOrNew($locale)->value = $request->value; 
							
			return $Defines;			 
		
	}


}
